from datetime import datetime
from sqlite3.dbapi2 import IntegrityError
from aiogram.types.user import User
from app.dates import get_now_datetime_str
from app.messages import Event, Notifications
from app.db import delete, fetchall, insert, select_by_keys

def add_notifications2db(notification_object: Notifications, meeting_id: int):
    for n in [notification_object.befor_day, notification_object.befor_4hours, notification_object.befor_5mins]:
        insert("notifications", {
            "when_notify": n.date_time_srting,
            "meeting_id": meeting_id,
            "chat_id": n.chat_id,
            "message": n.message
            })


def add_event2db(event: Event) -> int:
    return insert("meetings", {
        "description": event.agenda,
        "meeting_datetime": event.date_time,
        "participants": event.participants,
        "leader_id": event.organizer.id,
        "chat_id": event.chat_id,
        "meeting_link": event.meeting_url
        })


def check_notifications_now():
    date_time_str = get_now_datetime_str()
    result = select_by_keys("notifications", ["chat_id", "message"],
            {"when_notify": date_time_str})
    return result if type(result) == list else [result]

def get_user_by_id(user_id):
    return select_by_keys(
        'users',
        ["id", "firstname", "lastname", "login"],
        {'id': str(user_id)})


def get_all_users():
    return fetchall("users", ["id", "firstname", "lastname", "login"])


def del_user_by_id(user_id):
    delete('users', user_id)



def add_user2db(user: User):
    try:
        return insert("users", {
                "id":           user.id,
                "firstname":    user.first_name,
                "lastname":     user.last_name,
                "login":        user.username
            })
    except IntegrityError:
        pass
